<template>
  <el-dialog
    :visible.sync="isShow"
    :close-on-click-modal="false"
    append-to-body
    width="800px"
    :title="title"
    @close="cancel"
  >
    <div class="search_box">
      <el-input
        placeholder="请输入关键词进行搜索"
        v-model="keyword"
        style="width: 400px"
        @change="searchFn"
      ></el-input>
      <el-button type="primary" class="btn" @click="searchFn">搜索</el-button>
      <el-button
        type="primary"
        plain
        class="btn"
        @click="back"
        v-show="pageState == 3||pageState == 2"
        >返回</el-button
      >
    </div>
    <!-- v-infinite-scroll="nextPage" -->
    <div
      v-show="pageState == 1 || pageState == 3"
      class="msg_history_box"
      ref="msgListBox"
      v-infinite-scroll="nextPage"
      v-loading="loading"
    >
      <div
        class="msg_item"
        :id="'msg_' + msg.id"
        v-for="(msg, i) in msgList"
        :key="i"
      >
        <div class="other_msg msg" >
          <div class="avatar" >
            <img
              :src="msg.fromUserAvatar"
              alt="头像"
            />
          </div>
          <div class="msg_cont">
            <div class="name">
              <span >{{ msg.fromUserName }}</span>
              <span class="time">{{ msg.createTime }}</span>
            </div>
            <span class="msg_info">
              <template v-if="msg.type == 'text'">
                <span v-html="messageStyle(msg.content)"></span>
              </template>
              <template v-if="msg.type == 'custom'">
                <div class="img_msg" v-if="msg.customType == 'image'">
                  <el-image
                    fit="contain"
                    :src="msg.content"
                    class="img"
                    :preview-src-list="viewImgUrls"
                    :initial-index="getImgIndex(msg.content)"
                  ></el-image>
                </div>
                <div class="img_msg" v-else-if="msg.customType == 'video'">
                  <video :src="msg.content" class="img video" controls></video>
                </div>
                <!-- 商品链接消息 -->
                <div class="goods_msg" v-else-if="msg.customType === 'goods'" @click="goGoodsDetail(formatGoods(msg.content).link)">
                  <div class="img">
                    <img class="" style="border-radius: 5px;" :src="formatGoods(msg.content).titleImg" fit="contain" />
                  </div>
                  <div class="goods_cont">
                    <div>商品编号：{{formatGoods(msg.content).id}}</div>
                    <div class="goods_cont">{{ formatGoods(msg.content).des }}</div>
                    <div style="color:red;font-size:18px" v-if="formatGoods(msg.content).price">¥{{formatGoods(msg.content).price}}</div>
                  </div>
                </div>
                <div v-else>
                  {{msg.content  }}
                </div>
              </template>
            </span>
          </div>
        </div>
      </div>
    </div>
    <div v-show="pageState == 2" class="msg_history_box msg_search_box" v-loading="loading">
      <template v-if="searchResultList&&searchResultList.length">
        <div class="msg_item" v-for="(msg, i) in searchResultList" :key="i">
          <div class="other_msg msg">
            <div class="avatar" >
              <img
                :src="msg.fromUserAvatar"
                alt="头像"
              />
            </div>
            <div class="msg_cont">
              <div class="name">
                <span>{{ msg.fromUserName }}</span>
                <span class="time">{{ msg.createTime }}</span>
              </div>
              <div class="msg_info">
                <div class="txt_msg" v-if="msg.type == 'text'">
                  {{ msg.content }}
                </div>
              </div>
            </div>
          </div>
          <div>
            <el-button type="text" @click="viewSXW(msg)">查看上下文</el-button>
          </div>
        </div>
      </template>
      <template v-else>
        <div style="font-size: 20px;line-height: 100px;text-align: center;">
          未找到聊天记录
        </div>
      </template>
      
    </div>
  </el-dialog>
</template>


<script>
// 自定义接口
import { getHistoryMessageCustom, searchInSession } from "../../../api/custom";
export default {
    props: {
    showDialog: {
      type: Boolean,
      default: () => false,
    },
    sessionId:{
      type:String,
      default:() => {}
    }
  },
  data() {
    return {
      msgList: [],
      isHasPre: true,
      isHasNext: true,
      chatType: "singleChat",
      loading: false,
      // sessionId: "",
      searchResultList: [],
      pageState: 1,
      loginUserInfo: '',
      msgListBox: {},
      scrollTop: {},
      keyword: "",
      remarkList: '',
      time: "",
      title:'聊天记录',
      isShow:false
    };
  },
  computed: {
    messageStyle() {
      return (msg) => {
        // 将消息中的/n 替换成<br/>
        msg = msg.replace(/\n/g, "<br/>");
        if (msg.indexOf("@") > -1) {
          let arr1 = msg.split("@");
          let arr2 = arr1[1].split(" ");
          let user = "@" + arr2[0] + " ";
          arr2.shift();
          let lastmsg = "";
          if (arr2.length >= 1) {
            arr2.map((r) => {
              lastmsg = lastmsg + r;
            });
          }
          return `${arr1[0]}<span style="color:cornflowerblue;cursor:pointer">${user}</span>${lastmsg}`;
        } else {
          return msg;
        }
      };
    },
    viewImgUrls() {
      let arr = [];
      if (this.msgList && this.msgList.length) {
        for (let i = 0; i < this.msgList.length; i++) {
          let msg = this.msgList[i];
          if (msg.customType === "image") {
            arr.push(msg.content);
          }
        }
      }
      return arr;
    },
    getImgIndex() {
      return (img) => {
        return this.viewImgUrls.indexOf(img);
      };
    },
    formatGoods(){
      return (msg) => {
        let obj = {}
          if (msg) {
              // obj = JSON.parse(JSON.stringify(msg))
              let arr1 = msg.split('&&&')
              if (arr1 && arr1.length) {
                  arr1.map((r) => {
                      let arr2 = r.split('@#$')
                      obj[arr2[0]] = arr2[1]
                  })
              }
          }
          return obj
      }
    },
    tenantInfo() {
      return this.$store.getters.shopInfo;
    },

  },
  created() {
  },
  methods: {
    // 打开商品详情页
goGoodsDetail(link){
    let str = this.tenantInfo.domain
    if (str.indexOf(',') > -1) {
        str = str.split(',')[0]
    }
    if (link.indexOf('http') == -1) {
        link = 'http://' + str + link
    }
    window.open(link)
},
    scrollListenerHandler() {
      this.scrollTop = this.$refs.msgListBox.scrollTop;
    },
    prePage() {
      let firstId;
      if (this.msgList && this.msgList.length) {
        firstId = this.msgList[0].id;
      }
      this.getMsgListPage(firstId, 1, 20);
    },
    nextPage() {
      // 最后一个消息id
      // 滚动到底部
      if (this.msgList && this.msgList.length) {
        let lastId = this.msgList[this.msgList.length - 1].id;
        this.getMsgListPage(lastId, 2, 20);
      }
    },
    // 获取分页消息
    getMsgListPage(id, type, limit) {
      if (
        (this.isHasPre && type == 1) ||
        (this.isHasNext && type == 2) ||
        type == 3
      ) {
        this.loading = true;
        getHistoryMessageCustom(this.sessionId, id, type, limit).then((res) => {
      
          this.loading = false;
          if (type == 1) {
            // 上一页
            this.msgList = res.rows.concat(this.msgList);
            this.scrollMessageList(id);
            if (res.rows.length == 0) {
              this.isHasPre = false;
            }
          } else if (type == 2) {
            // 下一页
            this.msgList = this.msgList.concat(res.rows);
            if (res.rows.length == 0) {
              this.isHasNext = false;
            }
          } else if (type == 3) {
            this.msgList = res.rows;
          }
        });
      }
    },
    //搜索记录
    searchFn() {
      // keyword
      searchInSession(this.sessionId, this.keyword).then((res) => {
        this.pageState = 2;
        this.searchResultList = res.rows;
      });
    },
    viewSXW(msg) {
      //
      this.isHasPre = true;
      this.isHasNext = true;
      getHistoryMessageCustom(this.sessionId, msg.id, 3, 10).then((res) => {
        this.pageState = 3;
        this.msgList = res.rows;
        this.scrollMessageList(msg.id);
      });
    },
    back() {
      if (this.pageState == 3) {
        this.pageState = 2;
      }
      else if (this.pageState == 2) {
        this.pageState = 1;
      }
    },
    cancel() {
      this.$emit("close");
    },
    scrollMessageList(msgId) {
      //direction滚动方向 bottom向下滚动 normal向上滚动

      this.$nextTick(() => {
        const currentMsgEl = document.getElementById("msg_" + msgId);
        currentMsgEl.scrollIntoView(true);
      });
    },
  },


  watch: {
    "showDialog": {
      handler(newVal, oldVal) {
        if (newVal == true) {
          this.isShow = true
          this.pageState = 1;
          this.$nextTick(() => {
            this.isHasPre = true;
            this.msgListBox.scrollTop = 10000;
            this.$refs.msgListBox.addEventListener("scroll", this.scrollListenerHandler);
          });
          this.keyword = "";
        
          if (this.sessionId) {
            getHistoryMessageCustom(this.sessionId).then((res) => {
            
              this.msgList = res.rows;
              if (res.rows && res.rows.length) {
                this.scrollMessageList(res.rows[res.rows.length - 1].id);
              }
            });
          }
        } else {
          this.isShow = false
        }
      },
      immediate: true,
      deep: true,
    },
    'scrollTop': {
      handler(newVal, oldVal) {
        if (newVal == 0) {
        //   // 请求上一页
          this.prePage();
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.search_box {
  display: flex;
  // margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;

  .btn {
    margin-left: 10px;
  }
}
.time {
    margin-left: 10px;
  }
.msg_history_box {
  padding: 10px;
  padding-top: 10px;
  width: 100%;
  height: calc(100vh - 400px);
  overflow-y: auto;
  // border: 1px solid #e0dfdf;
  box-sizing: border-box;
  // background-color: #fff;
  border-top: 3px solid #79bbff;
  background-color: #f9f9f9;

  .msg_item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

  }

  .avatar {
    img {
      border-radius: 50%;
      width: 50px;
      height: 50px;
    }
  }

  .msg {
    display: flex;
    
    .msg_cont {
      max-width: 500px;
      
    }

    .name {
      color: #999;
      margin-bottom: 10px;
      >span{
        display: inline-block;
        width: 200px;overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: top;
      }
    }
  }
  .msg_info {
    display: inline-block;
    background-color: #fff;
    padding: 10px;
    border-radius: 5px;
    line-height: 22px;
  }



  .other_msg {
    .avatar {
      margin-right: 15px;
    }
  
  }

  .img_msg {
    // max-height: 200px;
    // width: 200px;
    .img {
      height: 200px;
      width: 100%;
    }
    .video {
      width: 350px;
    }
  }
}

.msg_search_box {
  background-color: #fff;
  .avatar {
    margin-right: 15px;
  }
  .msg_info {
    padding-left: 0 !important;
    padding-top: 0 !important;
  }
  .msg_item {
    padding: 5px 15px;
    border-bottom: 1px solid #f3f3f3;
  }

  
}


// 商品链接样式
.goods_msg {
    display: flex;
    width: 400px;
    cursor: pointer;

    .img {
        width: 100px;
        height: 100px;
        margin-right: 10px;
        flex-shrink: 0;

        img {
            width: 100%;
            height: 100%;
        }
    }

    .goods_tit {
        font-weight: 600;
        font-size: 16px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }

    .goods_cont {
        font-size: 14px;
        //max-height: 90px;
        line-height: 22px;
        overflow: hidden;
        // margin-top: 10px;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 4;
        &.huishoudes {
            -webkit-line-clamp: 2;
        }
    }
}
</style>